from fastapi import APIRouter, Query, Path
from fastapiApp.controllers.agvs_control import AGV_car_controller, AGV_position_controller
from fastapiApp.schemas.base_scheams import Success, SuccessExtra, Fail
from fastapiApp.schemas.agvs_scheams import *

router = APIRouter()


@router.get("/page", summary="获取配置列表")
async def list_agv_car(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=1000, description="每页数量")
):
    """
    获取AGV car列表,支持分页
    """
    total, data = await AGV_car_controller.list(page=page, page_size=page_size)
    return SuccessExtra(msg='获取成功', data=data, total=total, page=page, page_size=page_size)


@router.get("/all", summary="获取所有配置")
async def get_position():
    """
    获取所有配置信息 没有数据量限制
    """
    query = await AGV_position_controller.model.all()
    data_list = [await data.to_dict() for data in query]
    return Success(msg="获取所有配置成功", data=data_list)


@router.post("/create", summary="添加AGV car")
async def create_agv_car(obj_in: AGVcarCreate):
    """
    添加AGV car
    """
    await AGV_car_controller.is_exist(obj_in=obj_in)
    await AGV_car_controller.model.create(** obj_in.model_dump())
    return Success(msg="Created Successfully")


@router.delete("/delete/{id}", summary="删除AGV car")
async def delete_agv_car(id: int = Path(..., ge=0, description="ID")):
    """
    删除AGV car
    """
    obj = await AGV_car_controller.model.get_or_none(id=id)
    if obj:
        await obj.delete()
        return Success(msg=f"Deleted Success By ID = {id}")
    else:
        return Fail(msg=f"ID {id} 不存在")


@router.get("/detail/{id}", summary="查看AGV car详情")
async def get_agv_car_detail(id: int = Path(..., ge=1, description="ID")):
    """
    查看AGV car详情
    """
    obj = await AGV_car_controller.model.get_or_none(id=id)
    if obj:
        data = await obj.to_dict()
        return Success(msg="Success", data=data)
    else:
        return Fail(msg=f"ID {id} 不存在")


@router.put("/update", summary="更新AGV car")
async def update_agv_car(obj_in: AGVcarUpdate):
    """
    更新AGV car
    """
    await AGV_car_controller.update_agv_car(obj_in=obj_in)
    return Success(msg=f"Update Successfully By ID = {obj_in.id}")


@router.post("/enable", summary="启用AGV car")
async def enable_agv_car(id: int = Query(..., description="ID")):
    """
    启用AGV car
    """
    obj = await AGV_car_controller.model.get_or_none(id=id)
    if obj:
        obj.isenable = 1
        await obj.save()
        return Success(msg=f"Enable Success By ID = {id}")
    else:
        return Fail(msg=f"ID {id} 不存在")


@router.post("/disable", summary="禁用AGV car")
async def disable_agv_car(id: int = Query(..., description="ID")):
    """
    禁用AGV car
    """
    obj = await AGV_car_controller.model.get_or_none(id=id)
    if obj:
        obj.isenable = 0
        await obj.save()
        return Success(msg=f"Disable Success By ID = {id}")
    else:
        return Fail(msg=f"ID {id} 不存在")


@router.get("/position", summary="获取位置信息")
async def get_agv_position():
    """
    获取所有AGV的位置信息
    """
    data = await AGV_position_controller.get_all_position()
    return Success(data=data)


@router.post("/create_simulation", summary="新增虚拟设备")
async def create_agv_simulation(obj_in: AGVsimulationCreat):
    """
    新增虚拟设备
    """
    if await AGV_position_controller.model.filter(car_index=obj_in.car_index).exists():
        return Fail(code=401, msg="AGV编号已存在")
    
    # 转换输入数据为字典
    data = obj_in.model_dump()
    
    # 在Tortoise ORM中，直接使用foreign_key_id后缀设置外键ID值
    # 这是一种更直接的方式，不需要先获取模型对象
    simulation_data = {
        'car_index': data.get('car_index'),
        'x': data.get('x'),
        'y': data.get('y'),
        'angle': data.get('angle'),
        'speed': data.get('speed'),
        'is_connected': data.get('is_connected'),
        'status': data.get('status'),
        'battery': data.get('battery'),
        'simulation': data.get('simulation'),
    }
    
    # 只有当值不为null时才添加node_from_id_id和node_to_id_id字段
    if data.get('node_start_id') is not None:
        simulation_data['current_node_id'] = data.get('node_start_id')
    if data.get('node_to_id') is not None:
        simulation_data['node_to_id_id'] = data.get('node_to_id')
    
    # 直接创建记录，使用_id后缀确保外键ID被正确处理
    await AGV_position_controller.model.create(**simulation_data)
    
    return Success(msg="Created Successfully")


@router.delete("/delete_simulation", summary="删除虚拟设备")
async def delete_agv_simulation(id: int = Query(..., description="ID"),):
    """
    删除虚拟设备
    """
    obj = await AGV_position_controller.model.get_or_none(id=id)
    if obj:
        await obj.delete()
        return Success(msg=f"Deleted Success By ID = {id}")
    else:
        return Fail(msg=f"ID {id} 不存在")


@router.get("/namelist", summary="获取AGV编号列表")
async def get_agv_name_list():
    """
    获取AGV编号列表
    """
    query = await AGV_position_controller.model.filter().values_list("id","car_index")
    if query:
        return Success(msg="Success", data=list(query))
    else:
        return Fail(msg="名称列表为空")


@router.patch("/update_station_to/{id}", summary="更新目标站")
async def update_agv_station_to(id: int = Path(..., ge=1, description="ID"), node_to_id: int = Query(..., description="目标站ID")):
    """
    更新AGV car的目标站
    """
    obj = await AGV_position_controller.model.get_or_none(id=id)
    if obj:
        obj.node_to_id_id = node_to_id
        obj.status = AGVStatus.RUNNING
        await obj.save()
        return Success(msg=f"Update Success By ID = {id}")
    else:
        return Fail(msg=f"ID {id} 不存在")

